package com.project.service.base;

import com.project.entity.User;
import com.project.myBeans.BdXY;
import com.project.myBeans.ConfigParameters;
import com.project.myBeans.ResponseBean;
import com.project.shiro.credentials.RetryLimitHashedCredentialsMatcher;
import com.project.utils.Constants;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import it.sauronsoftware.base64.Base64;

/**
 * Created by TAO on 2016/3/22.
 */
public class BaseService {

    @Resource //自动注入sqlSessionTemplate
    public SqlSessionTemplate sqlSessionTemplate;

    @Autowired
    public ConfigParameters configParameters;

    public ModelAndView view = new ModelAndView();

    public ResponseBean responseBean = new ResponseBean();

    public static Logger log = Logger.getLogger(BaseService.class);

    public String getSuccessPage() {
        return "success";
    }

    public String getErrorPage() {
        return "error";
    }


    //用户登录处理
    public boolean userLogin(Subject subject, HttpServletRequest request, Session session) //session
    {
        if ("get".equalsIgnoreCase(request.getMethod())) {
            return false;
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return false;
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            return true;
        } catch (ExcessiveAttemptsException e) {
//            message.setCode(AppConstant.USERNAME_NOTEXIST);
//            message.setMsg("帐号被锁定10分钟");
            Cache<String, AtomicInteger> cache = RetryLimitHashedCredentialsMatcher.getPasswordRetryCache();
            if (null == cache.get(username + "locked")) {
                cache.put(username + "locked", new AtomicInteger(0));
            }
            e.printStackTrace();
            return false;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {

        }
    }

    //    //阿里大鱼
    public TaobaoClient getTaobaoClient() throws IOException {
//        Properties properties = new Properties();
//        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
//        properties.load(inputStream);//将属性文件流装载到Properties对象中
        TaobaoClient client = new DefaultTaobaoClient(configParameters.getAlidayuServer(),
                configParameters.getAppkey(),
                configParameters.getSecret());
        return client;
    }

//    //阿里大鱼
//    public AlibabaAliqinFcSmsNumSendRequest getAlidayuRequest(String phone, String code){
//        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
//        req.setSmsType("normal");
//        req.setSmsFreeSignName("优安士");
//        // req.setSmsParamString("{\"code\":\""+code+"\",\"product\":\"UAuth\"}");
//        req.setSmsParamString("{\"code\":\""+code+"\"}");
//        req.setRecNum(phone);
//        req.setSmsTemplateCode("SMS_3595164");
//        return  req;
//    }
//
//    public AlibabaAliqinFcSmsNumSendRequest getRequestForSpOnline(SpUN spUN,String phone){
//        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
//        req.setSmsType("normal");
//        req.setSmsFreeSignName("优安士");
//        req.setRecNum(phone);
//        req.setSmsParamString("{\"spname\":\""+spUN.getSpname()+"\",\"spid\":\""
//                +spUN.getSpid()+"\",\"sporgname\":\""+spUN.getOrgname()+
//                "\",\"spdeusername\":\""+spUN.getDeuserloginname()+"\"}");
//        req.setSmsTemplateCode("SMS_3600319");
//        return req;
//    }
//
//    public AlibabaAliqinFcSmsNumSendRequest getRequestForNewSp(SpUN spUN,String phone){
//        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
//        req.setSmsType("normal");
//        req.setSmsFreeSignName("优安士");
//        req.setRecNum(phone);
//        req.setSmsParamString("{\"spname\":\""+spUN.getSpname()+"\",\"spid\":\""
//                +spUN.getSpid()+"\",\"sporgname\":\""+spUN.getOrgname()+
//                "\",\"spdeusername\":\""+spUN.getDeuserloginname()+"\"}");
//        req.setSmsTemplateCode("SMS_3625186");
//        return  req;
//    }


    //生成短信验证码
    public String getSmsCode() {
        Random random = new Random();
        String code = "";
        int n;
        while (true) {
            n = random.nextInt(10);
//                if(code.contains(String.valueOf(n))) //控制验证码不出现重复数字
//                    continue;
            code += n;
            if (code.length() == 6) //验证码6位
                break;
        }
        return code;
    }

    //发起http请求
    public static String getUrl(String requestUrl, String Method, String bm) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod(Method);
            httpUrlConn.connect();

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, bm);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            System.out.println(buffer.toString() + "=======");
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            //inputStream = null;
            httpUrlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }


    //打印错误信息
    public void printErros(BindingResult result) {
        if (result.hasErrors()) {
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError err : errors) {
                System.out.println("ObjectName:" + err.getObjectName() + "\tFieldName:" + err.getField()
                        + "\tFieldValue:" + err.getRejectedValue() + "\tMessage:" + err.getDefaultMessage());
            }
        }
    }

    //判断字符串是否为整型数字
    public boolean isIntNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //格式化Mon Dec 12 15:00:14 CST 2011日期
    public static String getFormateDateStr(String str) {
        Date d = null;
        if (StringUtils.isEmpty(str)) {
            //log.error("DateUtils|getFormateDateStr入参为空");
            return null;
        }

        SimpleDateFormat sdfSource = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        SimpleDateFormat sdfTarget = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        try {
            d = sdfSource.parse(str);
        } catch (ParseException e) {
            //log.error("DateUtils|getFormateDateStr异常，入参为："+str+",错误信息："+e);
            return null;
        }
        return sdfTarget.format(d);
    }

    //TAO:IDList字符串形式转换为List<Long>
    public List<Long> getIdList(String idStr, String splitCahr) {
        String[] sourceStrArray = idStr.split(splitCahr);
        List<Long> idList = new ArrayList<Long>();
        for (int i = 0; i < sourceStrArray.length; i++) {
            idList.add(Long.parseLong(sourceStrArray[i]));
        }
        return idList;
    }

    //TAO:日期形式的字符串转换成日期类型
    public Date getDate(String dateStr) {
        DateFormat df = new SimpleDateFormat(Constants.DATEFORMAT.DATE.value());
        try {
            if (dateStr.isEmpty() || dateStr.equals("") || dateStr.length() == 0)
                return null;
            Date date = df.parse(dateStr);
            return date;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 生成md5
     *
     * @param message
     * @return
     */
    public static String getMD5(String message) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = message.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //获得session中的用户对象
//    public User getCurrentUser(HttpSession session){
//        User u= (User)session.getAttribute("currentUser");
//        return u;
//    }

    public String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        // 去掉"-"符号
        //String temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
        return str;
    }

    //TAO:日期形式的字符串转换成日期时间类型
    public Date getDateTime(String dateStr) {
        DateFormat df = new SimpleDateFormat(Constants.DATEFORMAT.DATETIME.value());
        try {
            if (dateStr.isEmpty() || dateStr.equals("") || dateStr.length() == 0)
                return null;
            Date date = df.parse(dateStr);
            return date;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //TAO:获取当前TIMESTAMP
    public Timestamp getCurrentTimeStamp2() {
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        return timestamp;
    }

    //gps坐标转bd坐标
    public BdXY gps2bd(double x, double y) {
        BdXY bdXY = new BdXY();
        //转换前的GPS坐标: x-经度,y-纬度
        //double x=116.397428; //经度
        //double y=39.90923;  //纬度
        //google 坐标转百度链接   //http://api.map.baidu.com/ag/coord/convert?from=2&to=4&x=116.32715863448607&y=39.990912172420714&callback=BMap.Convertor.cbk_3694
        //gps坐标的type=0
        //google坐标的type=2
        //baidu坐标的type=4
        String path = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=" + x + "+&y=" + y + "&callback=BMap.Convertor.cbk_7594";
        try {
            //使用http请求获取转换结果
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            //得到返回的结果
            String res = outStream.toString();
            System.out.println(res);
            //处理结果
            if (res.indexOf("(") > 0 && res.indexOf(")") > 0) {
                String str = res.substring(res.indexOf("(") + 1, res.indexOf(")"));
                String err = res.substring(res.indexOf("error") + 7, res.indexOf("error") + 8);
                if ("0".equals(err)) {
                    JSONObject js = JSONObject.fromObject(str);//编码转换
                    String x1 = new String(Base64.decode(js.getString("x")));
                    String y1 = new String(Base64.decode(js.getString("y")));

                    bdXY.setLatitude(Double.parseDouble(y1));
                    bdXY.setLongitude(Double.parseDouble(x1));

                    System.out.println(x1 + "::" + y1);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return bdXY;
        }
        return bdXY;
    }

    //WheelChen: 检查删除/更新是否成功
    /**
     * author: WheelChen
     * date: 2017/7/24
     * function: 检查删除/更新是否成功
     *
     * @param effectCol 受影响行数
     * @return
     */
    public void processSuccessDeleteUpdate(int effectCol, ResponseBean responseBean) {
        if (effectCol > 0) {
            responseBean.setSuccess(true);
            responseBean.setMessage("操作成功");
        } else {
            responseBean.setSuccess(false);
            responseBean.setMessage("操作失败");
        }
    }

    /**
     * author: WheelChen
     * date: 2017/8/9
     * function: 检查删除/更新是否成功
     *
     * @param effectCol 影响行数
     * @return
     */
    public boolean checkDeleteUpdateIsSuccess(int effectCol) {
        boolean flag = false;
        if (effectCol > 0) flag = true;
        return flag;
    }

    //WheelChen: 过滤敏感信息
    public void filterSensitiveInfo(User user){
        user.setUsername(null);
        user.setPassword(null);
        user.setSalt(null);
    }


}

